package com.zju.DoctorGo.controller;

import java.math.BigDecimal;
import java.util.List;

import com.alibaba.druid.sql.visitor.functions.BitLength;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zju.DoctorGo.dto.BillDTO;
import com.zju.DoctorGo.entity.Bill;
import com.zju.DoctorGo.mapper.BillMapper;
import com.zju.DoctorGo.mapper.DiagnosisMapper;
import com.zju.DoctorGo.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

import com.zju.DoctorGo.entity.Diagnosis;
import com.zju.DoctorGo.entity.Result;
import lombok.extern.slf4j.Slf4j;

@CrossOrigin
@RestController
@Slf4j
public class DiagnosisController {

    @Autowired
    private DiagnosisMapper diagnosisMapper;

    @Autowired
    private BillMapper billMapper;
    @Autowired
    private PaymentService paymentService;
    @PostMapping("/api/diagnosis")
    public Result createDiagnosis(@RequestBody Diagnosis diagnosis) {
        try {

            BillDTO billDto = new BillDTO();
            billDto.setPaymentPartyId(diagnosis.getPatientId());
            billDto.setPaymentPartyName(diagnosis.getPatientName());
            billDto.setInitiatorId(diagnosis.getDoctorId());
            billDto.setInitiatorName(diagnosis.getDoctorName());
            billDto.setAmount(new BigDecimal("0.01"));
            paymentService.createBill(billDto);
            diagnosis.setBillId(billDto.getBillId());
            diagnosisMapper.insert(diagnosis);
            return Result.success();
        } catch (DuplicateKeyException e) {
            log.error("Failed to create diagnosis due to duplicate key: {}", e.getMessage());
            return Result.error("A diagnosis with the same ID already exists. Please use a unique ID.");
        } catch (Exception e) {
            log.error("Failed to create diagnosis: {}", e.getMessage());
            return Result.error("An unexpected error occurred while creating the diagnosis.");
        }
    }

    @GetMapping("/api/diagnosis/getByPatientName")
    public Result queryDiagnosisByPatientName(@RequestParam("patientName") String patientName) {
        log.info("查询患者诊断记录，患者姓名: {}", patientName);
        try {
            List<Diagnosis> diagnoses = diagnosisMapper.selectList(new QueryWrapper<Diagnosis>().eq("patientName", patientName));
            return Result.success(diagnoses);
        } catch (Exception e) {
            log.error("查询诊断记录失败: {}", e.getMessage());
            return Result.error(e.toString());
        }
    }

    @GetMapping("/api/diagnosis/getById")
    public Result queryDiagnosisById(@RequestParam("diagnosisId") int diagnosisId) {
        log.info("查询诊断记录，诊断Id: {}", diagnosisId);
        try {
            Diagnosis diagnosis = diagnosisMapper.selectOne(new QueryWrapper<Diagnosis>().eq("diagnosisId", diagnosisId));
            return Result.success(diagnosis);
        } catch (Exception e) {
            log.error("查询诊断记录失败: {}", e.getMessage());
            return Result.error(e.toString());
        }
    }

    @GetMapping("/api/diagnosis/getByStatus")
    public Result queryDiagnosisByStatus(@RequestParam("diagnosisStatus") String diagnosisStatus) {
        try {
            List<Diagnosis> diagnoses = diagnosisMapper.selectList(new QueryWrapper<Diagnosis>().eq("diagnosisStatus", diagnosisStatus));
            return Result.success(diagnoses);
        } catch (Exception e) {
            log.error("查询诊断记录失败: {}", e.getMessage());
            return Result.error(e.toString());
        }
    }

    @GetMapping("api/diagnosis/getByDoctorId")
    public Result getDiagnosesByDoctorId(@RequestParam("doctorId") Integer doctorId) {
        try {
            List<Diagnosis> diagnoses = diagnosisMapper.selectList(new QueryWrapper<Diagnosis>().eq("doctorId", doctorId));
            return Result.success(diagnoses);
        } catch (Exception e) {
            log.error("查询诊断记录失败: {}", e.getMessage());
            return Result.error(e.toString());
        }
    }

    @DeleteMapping("/api/diagnosis/{diagnosisId}")
    public Result deleteDiagnosis(@PathVariable int diagnosisId) {
        log.info("Deleting diagnosis with ID: {}", diagnosisId);
        try {
            int isDeleted = diagnosisMapper.deleteById(diagnosisId);
            if (isDeleted != 0) {
                return Result.success();
            } else {
                return Result.error("Fail to delete, diagnosis doesn't exist");
            }
        } catch (Exception e) {
            log.error("Failed to delete diagnosis: {}", e.getMessage());
            return Result.error("An error occurred while deleting the diagnosis.");
        }
    }
}
